/* Created on May 2, 2007 */
/**
   Copyright (C) 2007 by AKrasnopolski (Alexei Krasnopolski)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. 
*/

package com.ak.webcme;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * The <tt>WebCMEServlet</tt> class 
 * <p>
 * @version 1.0.0
 * @author <a href="mailto:krasnop@bellsouth.net">Alexei Krasnopolski</a>
 */
public class WebCMEServlet extends HttpServlet
{
  protected final Logger log = Logger.getLogger( "WebCMEServlet" );
  @Override
  protected void doGet( HttpServletRequest rqst, HttpServletResponse resp ) throws ServletException, IOException
  {
    doPost( rqst, resp );
  }

  @Override
  protected void doPost( HttpServletRequest rqst, HttpServletResponse resp ) throws ServletException, IOException
  {
    StringBuffer sb = new StringBuffer();
    String completionCode = "success";
    
    for(Enumeration en = rqst.getParameterNames(); en.hasMoreElements(); )
    {
      String pName = (String)en.nextElement();
      sb.append( pName ).append( " = " ).append( rqst.getParameter( pName ) ).append( "\r\n" ); 
    }
    log.debug( "\r\n parameter names = \r\n" + sb.toString() ); 

    File file = new File( getServletContext().getRealPath( "html/iframe.html" ) );
    if( file != null )
    {
      log.debug( " file name = " + file.getName() );
      PrintWriter fileWriter = new PrintWriter( file );
      fileWriter.write( rqst.getParameter( "content" ) );
      fileWriter.flush();
      fileWriter.close();
    }
    else
    {
      log.debug( " file is null " );
      completionCode = "error";
    }
    
    PrintWriter out = resp.getWriter();
    out.print( completionCode );
    out.close();
    
  }

  @Override
  public void destroy()
  {
    super.destroy();
  }

  @Override
  public void init( ServletConfig conf ) throws ServletException
  {
    super.init( conf );
    log.debug( ">>> init : " + conf.getInitParameter( "param0" ) );
  }
}
